﻿using Cdn.Blogger.Models;
using System;
using Local;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using XZen.Blogger;


namespace Cdn.Blogger.Controllers
{
   

    [EnsureMagazineContext]
    public class MagazineController : Controller
    {
        ReportData UI;

       
        public MagazineController()
        {
            UI = new ReportData(this);
        }
        



        public ActionResult Index()
        {
            var mags = Service.GetMagazines();
            return View(mags);
        }
        //
        // GET: /Magazine/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        public ActionResult CreateChapter(string id)
        {
            Chapter chapter = new  Chapter();
            chapter.IssueID = id;
            chapter.Articles = new List<Article>();
            return View(chapter);
        }
        [HttpPost]
        public ActionResult CreateChapter(Chapter chapter)
        {
            try
            {
                chapter.IP = this.GetVisitorIpAddress();
                var chapterId = this.Service.CreateChapter(chapter.IssueID.ToNullableLong(), chapter);
                UI.AddLine("Added Chapter!!");
                return RedirectToAction("EditChapter", new { id = chapterId });
            }
            catch(Exception cx)
            {
                UI.AddLine("Cant add chapter..." + cx.Message, ReportType.Error);
                return View(chapter);
            }
        }
        public ActionResult EditChapter(string id)
        {
            Chapter chapter = this.Service.GetChapter(id.ToNullableLong());
            chapter.Articles = this.Service.GetArticles(id.ToNullableLong());
            return View(chapter);
        }
        [HttpPost]
        public ActionResult EditChapter(Chapter chapter)
        {
            try
            {
                chapter.IP = this.GetVisitorIpAddress();
                chapter = this.Service.EditChapter(chapter);
                UI.AddLine("Edited Chapter!!");
                return RedirectToAction("EditChapter", new { id = chapter.ToID() });
            }
            catch(Exception cx)
            {
                chapter.Articles = this.Service.GetArticles(chapter.ID.ToNullableLong());
                UI.AddLine("Cant edit chapter..." + cx.Message, ReportType.Error);
                return View(chapter);
            }
        }
       

        public ActionResult EditIssue(string id)
        {
            Issue issue = this.Service.GetIssue(id.ToNullableLong());
            issue.Chapters = this.Service.GetChapters(id.ToNullableLong());
            return View(issue);
        }
        [HttpPost]
        public ActionResult EditIssue(Issue issue)
        {
            try
            {
                issue.IP = this.GetVisitorIpAddress();
                issue = this.Service.EditIssue(issue);
                UI.AddLine("Successfully edited the issue.", ReportType.Success);
                return RedirectToAction("EditIssue", new { id = issue.ToID() });
            }
            catch(Exception vcx)
            {
                issue.Chapters = this.Service.GetChapters(issue.ID.ToNullableLong());
                UI.AddLine("Cant edit issue..." + vcx.Message, ReportType.Error);
                return View(issue);
            }
        }

        
        public ActionResult CreateIssue(string id)
        {
            Issue issue = new Issue();
            issue.MagazineID = id;
            issue.Chapters = new List<Chapter>();
            return View(issue);
        }
        [HttpPost]
        public ActionResult CreateIssue(Issue issue)
        {
            try
            {
                issue.IP = this.GetVisitorIpAddress();
                var issueId = this.Service.CreateIssue(issue.MagazineID.ToNullableLong(), issue);
                UI.AddLine("Created the issue!");
                return RedirectToAction("EditIssue", new { id = issueId });
            }
            catch(Exception cx)
            {
                UI.AddLine("Cant add issue..." + cx.Message, ReportType.Error);
                return View(issue);
            }
        }
       

        //
        // GET: /Magazine/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Magazine/Create

        [HttpPost]
        public ActionResult Create(Magazine magazine)
        {
            try
            {
                magazine.IP = this.GetVisitorIpAddress();
                long? magId = this.Service.CreateMagazine(magazine);
                UI.AddLine("Magazine created!!", ReportType.Success);
                return RedirectToAction("Edit", new  {id=magId });
            }
            catch(Exception cx)
            {
                UI.AddLine("Cant create magazine!! " + cx.Message, ReportType.Error);
                return View();
            }
        }


        [HttpPost]
        public string CreateMagazine(Magazine magazine)
        {
            try
            {
                magazine.IP = this.GetVisitorIpAddress();
                magazine.Name = magazine.Title;
                long? magId = this.Service.CreateMagazine(magazine);
                UI.AddLine("Magazine created!!", ReportType.Success);
                magazine.ID = magId.ToString();
                return Newtonsoft.Json.JsonConvert.SerializeObject(magazine);
            }
            catch (Exception cx)
            {
                UI.AddLine("Cant create magazine!! " + cx.Message, ReportType.Error);
                return Newtonsoft.Json.JsonConvert.SerializeObject(cx);
            }
        }

        //
        // GET: /Magazine/Edit/5

        public ActionResult BindBook(string  id)
        {
            var mag = this.Service.GetMagazine(id.ToNullableLong());
            mag.Issues = this.Service.GetIssues(mag.ToID());
            return View(mag);
        }

        public ActionResult Edit(string id)
        {
            var mag = this.Service.GetMagazine(id.ToNullableLong());
            mag.Issues = this.Service.GetIssues(mag.ToID());
            return View(mag);
        }

        //
        // POST: /Magazine/Edit/5

        [HttpPost]
        public ActionResult Edit(Magazine magazine)
        {
            try
            {
                magazine.IP = this.GetVisitorIpAddress();
                this.Service.EditMagazine(magazine);
                UI.AddLine("Magazine updated !!", ReportType.Success);
                return RedirectToAction("Index");
            }
            catch(Exception cx)
            {
                UI.AddLine("Cant edit magazine!! " + cx.Message, ReportType.Error);
                return View();
            }
        }

        //
        // GET: /Magazine/Delete/5

        public ActionResult Delete(string  id)
        {
            var mag = this.Service.GetMagazine(id.ToNullableLong());
            mag.Issues = this.Service.GetIssues(mag.ToID());
            return View(mag);
        }

        //
        // POST: /Magazine/Delete/5

        [HttpPost]
        public ActionResult Delete(string  id, FormCollection collection)
        {
            try
            {
                var mag = this.Service.GetMagazine(id.ToNullableLong());
                this.Service.DeleteMagazine(mag);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public string Upload(string id, string ob)
        {
            long? folderId = id.ToNullableLong();

            FileStatus upload = new FileStatus();
            string callback = Request.Form["fd-callback"];
            upload.Callback = callback;
            string fileName;
            byte[] data;

            // Upload data can be POST'ed as raw form data or uploaded via <iframe> and <form>
            // using regular multipart/form-data enctype (which is handled by ASP.NET Request.Files).
            var fdFile = Request.Files["fd-file"];
            if (fdFile != null)
            {
                // Regular multipart/form-data upload.
                fileName = fdFile.FileName;
                data = new byte[fdFile.ContentLength];
                fdFile.InputStream.Read(data, 0, fdFile.ContentLength);

                upload.Name = fileName;
                upload.Size = fdFile.ContentLength;

            }
            else
            {
                // Raw POST data.
                fileName = HttpUtility.UrlDecode(Request.Headers["X-File-Name"]);
                data = new byte[Request.InputStream.Length];
                Request.InputStream.Read(data, 0, (int)Request.InputStream.Length); //up to 2GB

                upload.Name = fileName;
                upload.Size = (int)Request.InputStream.Length;
            }

            // Output message for this demo upload. In your real app this would be something
            // meaningful for the calling script (that uses FileDrop.js).
            byte[] md5Hash;
            using (MD5 md5 = MD5.Create())
            {
                md5Hash = md5.ComputeHash(data);

            }
            string output = string.Format("{0}; received {1} bytes, MD5 = {2}", fileName, data.Length, BytesArrayToHexString(md5Hash));
            upload.MD5 = BytesArrayToHexString(md5Hash);
            //string path = Server.MapPath("~/Content/Uploaded");
            
            // System.IO.File.WriteAllBytes(path + "\\" + name, data);

            upload.Url = this.Service.GetFileUrl(folderId, ob, data, fileName);
            // In FileDrop sample this demonstrates the passing of custom ?query variables along
            // with an AJAX/iframe upload.
            string opt = Request["upload_option"];
            upload.Option = opt;

            if (!string.IsNullOrEmpty(opt))
            {
                output += "\nReceived upload_option with value " + opt;
            }

            if (!string.IsNullOrEmpty(callback))
            {
                output = HttpUtility.JavaScriptStringEncode(output);
                output += "<!DOCTYPE html><html><head></head><body><script type=\"text/javascript\">" +
                   "try{window.top." + callback + "(\"" + output + "\")}catch(e){}</script></body></html>";
                return output;
            }
            else
            {
                output = Newtonsoft.Json.JsonConvert.SerializeObject(upload);
                return output;
            }
        }
        public string BytesArrayToHexString(byte[] hash)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
        MagazineService service;

        public MagazineService Service
        {
            get { return service; }
            set { service = value; }
        }
        protected string logOnUrl;

        public ActionResult Logon()
        {
            return RedirectToAction("Login", "Home", new { });
        }
        public ActionResult Login(string ContentSetting = null)
        {
            CDNSetting setting = new CDNSetting();
            setting.ContentUri = "http://localhost";
            setting.Password = "$Rijusmit2014";
            setting.Subscription = "blogger";
            setting.User = "rijusmit";
            setting.UserName = "rijusmit";

            if (ContentSetting == "ContentSetting")
            {
                string connectoinstring = ConfigurationManager.AppSettings["ContentSetting"];
                //CDNSetting setting = new CDNSetting();
                setting.Parse(connectoinstring);
                Init(setting);
            }
            return View(setting);
        }

        [HttpPost]
        public ActionResult Login(CDNSetting setting)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Exception failx = Init(setting);
                    if (failx == null)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ModelState.AddModelError("Validation", "The settings you have added is not valid because " + failx.Message);
                        ViewBag.Error = "The settings you have added is not valid because " + failx.Message;
                    }
                }
                catch (Exception cools)
                {
                    ModelState.AddModelError("Validation", "The settings you have added is not valid because " + cools.Message);
                    ViewBag.Error = "The settings you have added is not valid because " + cools.Message;
                }
            }
            return View(setting);
        }
        protected Exception Init(CDNSetting setting)
        {
            Exception result;
            try
            {
                this.service = MagazineService.Create(setting.User, setting.Password, setting.ContentUri, setting.Subscription);
                base.Session["MagazineService.Instance"] = this.service;
            }
            catch (Exception exds)
            {
                if (!base.Request.IsLocal)
                {
                    result = exds;
                    return result;
                }
            }
            result = null;
            return result;
        }
        //
        // GET: /Magazine/

    }
}
